package com.scm.servlet.pomain;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.scm.dao.PoitemDao;
import com.scm.dao.PomainDao;
import com.scm.dao.ProductDao;
import com.scm.dao.VenderDao;
import com.scm.model.Poitem;
import com.scm.util.DbUtil;

@WebServlet("/main/pomain/DelPomain")
public class DelPomainServlet extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String poId = req.getParameter("poId").trim();
		String currentPage = req.getParameter("currentPage");
		Connection conn = null;
		//事务处理
			try {
				conn = DbUtil.getConn();
				conn.setAutoCommit(false);
				PomainDao pomaindao = new PomainDao(conn);
				PoitemDao poitemdao = new PoitemDao(conn);
				//修改产品表在途数
				List<Poitem> poitems = new ArrayList<Poitem>();
				poitems = poitemdao.selectByPoid(Long.parseLong(poId));
				for(int n=0;n<poitems.size();n++) {
					String productCode = poitems.get(n).getProductCode();
					int number = -poitems.get(n).getNum();
					int delnum = new ProductDao(conn).changePONum(productCode, number);
					if(delnum == 0){
						conn.rollback();//回滚事务
						return;
					}
				}
				int k = poitemdao.deleteByPoid(Long.parseLong(poId));
				int i = pomaindao.del(poId);
				if(k == 0){
					conn.rollback();//回滚事务
					return;
				}
				if(i == 0) {
					conn.rollback();//回滚事务
					return;
				}
				conn.commit();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally {
				DbUtil.close(conn, null, null);
			}
		
		req.getRequestDispatcher("ListNewPomain?poId=null&currentPage="+currentPage).forward(req, resp);
	}

}
